package Solutions

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isBalanced(root *TreeNode) bool {
	_, ok := dfs__(root)
	return ok
}
func dfs__(root *TreeNode) (int, bool) {
	if root == nil {
		return 0, true
	}
	t1, b1 := dfs__(root.Left)
	t2, b2 := dfs__(root.Right)
	if !b1 || !b2 {
		return 0, false
	}
	if abs(t1, t2) > 1 {
		return 0, false
	}
	if t1 < t2 {
		return t2 + 1, true
	} else {
		return t1 + 1, true
	}

}
func abs__(i, j int) int {
	if i < j {
		return j - i
	} else {
		return i - j
	}
}
